package com.example.musicplayer.playtask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.AsyncTask;

import com.example.musicplayer.listener.MusicPlayListener;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.utils.LogUtil;

import java.io.IOException;

/**
 * @Author: liuzh0705
 * @Date:2021-07-30 下午7:10
 * @Description: 异步播放音乐
 */
public class MusicPlayTask extends AsyncTask<String, Integer, Integer> {

    private static final int MUSIC_ON_START_MUSIC = 0; // 开始播放音乐

    private static final int MUSIC_ON_STOP_MUSIC = 1; // 暂停播放音乐

    private static final int MUSIC_ON_UP_MUSIC = 2; // 上一曲

    private static final int MUSIC_ON_NEXT_MUSIC = 3; // 下一曲

    private MusicPlayListener musicPlayListener;

    private static MediaPlayer mediaPlayer;

    private static boolean isPlaying = false;

    private boolean isStopping = false;

    private int lastProgress;

    public MusicPlayTask(MusicPlayListener musicPlayListener, MediaPlayer mediaPlayer) {
        this.musicPlayListener = musicPlayListener;
        this.mediaPlayer = mediaPlayer;
    }

    /**
     * 后台播放/暂停的任务
     * @param params
     * @return
     */
    @Override
    protected Integer doInBackground(String... params) {
        String musicPath = params[0];
        try {
            if (!mediaPlayer.isPlaying()) {
                // 如果没有播放就播放
                mediaPlayer.reset();
                mediaPlayer.setDataSource(musicPath);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } else {
                // 如果有播放就切换歌曲播放
                mediaPlayer.reset();
                mediaPlayer.setDataSource(musicPath);
                mediaPlayer.prepare();
                mediaPlayer.start();
            }
            isPlaying = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
    }


    public static class MyTaskReciver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            } else {
                mediaPlayer.start();
            }
        }
    }
}


